﻿using Ec.NETCoreFramework.Common;
using Ec.NETCoreFramework.Common.Core.Helpers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Xml;
using System.Diagnostics;
using Ec.NETCoreFramework.Common.Core;
using Ec.NETCoreFramework.Common.Plug.Core;
using Ec.NETCoreFramework.Common.Clients;
using System.Linq;
using Ec.NETCoreFramework.Common.Core.Utilities;

namespace MQ_WechatCustomContact
{
    /// <summary>
    /// 聊天群拉取
    /// </summary>
    public class GroupChat : ICustomContact
    {
        private ConsumeConfig _consumeConfig;
        private string logTitle = "groupchat";
        private RequestAppSecret _appSecret;
        private string _SoftwareVersion = string.Empty;

        public GroupChat(RequestAppSecret appSecret)
        {
            _appSecret = appSecret;
            _SoftwareVersion = AppsettingsHelper.app(new string[] { "SoftwareVersion" });

        }
        public async Task Excute(ConsumeConfig consumeConfig)
        {
            _consumeConfig = consumeConfig;

            var stopwatch = new Stopwatch();
            stopwatch.Start();
            //拉数据
            try
            {
                var groupChatList = new List<GroupChatOutput>();
                //批量获取群组
                await GetGroupChatList(groupChatList,string.Empty);
                //获取群聊详情
                await GetGroupChatDetail(groupChatList);

                stopwatch.Stop();
                Console.WriteLine($"【{_consumeConfig.Domain}-{logTitle}-{_SoftwareVersion}】此次执行结束，耗时{stopwatch.ElapsedMilliseconds}ms");
            }
            catch (Exception ex)
            {

                if (stopwatch.IsRunning)
                {
                    stopwatch.Stop();
                }
                Console.WriteLine($"【{logTitle}】:{ex.Message}");
            }
        }

        /// <summary>
        /// 递归批量拉取外部联系人
        /// </summary>
        /// <param name="item"></param>
        /// <param name="cursor"></param>
        /// <returns></returns>
        private async Task GetGroupChatList(List<GroupChatOutput> list,string cursor)
        {
            var dic = new Dictionary<string, object>()
            {
                {"fk_id",_consumeConfig.FKId },
                {"db_id",_consumeConfig.DBId },
                //{"user_id",item.WXUserId },
                {"cursor",cursor }
            };
            var result = await new ApiRequestClient(_appSecret).
            GetResponse<JObject>(_consumeConfig.WechatDomain,
            string.Empty, dic, "/wx/groupchat/list", new Dictionary<string, string>() { { "api-version", "2.0" }, { "version", _SoftwareVersion } }, 10000);
            if (!result.Success) return;

            var re = ((IResponse<JObject>)result).Content;

            var follow_users = re["group_chat_list"] as JArray;
            foreach (JObject g in follow_users)
            {
                list.Add(new GroupChatOutput()
                {
                    ChatId = g["chat_id"].ToString(),
                    Status = Utils.ToInt(g["status"].ToString())
                });
            }

            if (!re.ContainsKey("cursor")) return;

            cursor = re["cursor"].ToString();
            if (string.IsNullOrEmpty(cursor)) return;

            await GetGroupChatList(list, cursor);
        }
        /// <summary>
        /// 批量拉取外部联系人
        /// </summary>
        /// <returns></returns>
        private async Task GetGroupChatDetail(List<GroupChatOutput> list)
        {
            foreach (var item in list)
            {
                await GetGroupChatDetail(item);
            }

        }
        /// <summary>
        /// 递归批量拉取外部联系人
        /// </summary>
        /// <param name="item"></param>
        /// <param name="cursor"></param>
        /// <returns></returns>
        private async Task GetGroupChatDetail(GroupChatOutput item)
        {
            var dic = new Dictionary<string, object>()
            {
                {"fk_id",_consumeConfig.FKId },
                {"db_id",_consumeConfig.DBId },
                {"fk_flag","2" },
                {"chat_id",item.ChatId }
            };
            var result = await new ApiRequestClient(_appSecret).
            GetResponse<JObject>(_consumeConfig.WechatDomain,
            string.Empty, dic, "/wx/groupchat/detail", new Dictionary<string, string>() { { "api-version", "2.0" }, { "version", _SoftwareVersion } }, 10000);
            if (!result.Success) return;

            var re = ((IResponse<JObject>)result).Content;
            var group_chat = re["group_chat"] as JObject;
            group_chat["status"] = item.Status;
            await Push(re);

        }
        /// <summary>
        /// 推数据
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        private async Task Push(JObject obj)
        {
            var xml = Json.JsonToXml(obj,"root");
            var dic = new Dictionary<string, object>()
                {
                    {"fk_id",_consumeConfig.FKId },
                    {"XML",xml.OuterXml }
                };

           var result=  await new ApiRequestClient(_appSecret).
        PostBinary<JObject>(_consumeConfig.Domain,
        "wxgroup.store.wxgroups.syncgroups", dic);
            if (!result.Success)
            {
                Console.WriteLine($"【{logTitle}】:{result.Message};{dic.ToLinkString() }");
            }


        }
    
    }
}
